package com.blockmeta.bbs.businesslibrary.umeng;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.LogUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ScrollView;
import android.widget.TextView;

import com.blockmeta.bbs.baselibrary.base.adapter.BaseAdapter;
import com.blockmeta.bbs.baselibrary.utils.DimentionsUtil;
import com.blockmeta.bbs.baselibrary.utils.FormatUtil;
import com.blockmeta.bbs.baselibrary.utils.ImageTools;
import com.blockmeta.bbs.baselibrary.utils.ToastUtil;
import com.blockmeta.bbs.businesslibrary.R;
import com.blockmeta.bbs.businesslibrary.voice.FileUtil;
import com.chad.library.adapter.base.BaseViewHolder;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by AirThor
 * Date 2018/1/10.
 * 截屏工具类
 */

public class ScreenShotUtil {

    public static File ScreenShot(int width, View view, Activity context) {
        int height = width / 3;
        View header = LayoutInflater.from(context).inflate(R.layout.view_header, null);
        TextView time = (TextView) header.findViewById(R.id.tv_save_time);
        time.setText(FormatUtil.getTimetoHMS(System.currentTimeMillis(), "yyyy-MM-dd HH:mm"));

        viewLayout(header, width, height);
        Bitmap headBitmap = createBitmap(header);

        int headerHeight = headBitmap.getHeight();

        Bitmap targetBitmap = shotRecyclerView((RecyclerView) view, headerHeight, headBitmap);

        String name = System.currentTimeMillis() + ".jpg";

        File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + File.separator + name);

        try {
            FileOutputStream outputStream = new FileOutputStream(file);
            targetBitmap.compress(Bitmap.CompressFormat.JPEG, 40, outputStream);
            targetBitmap.recycle();
            outputStream.flush();
            outputStream.close();
            MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), file.getName(), null);
            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_STARTED, Uri.parse("file://" + file.getAbsolutePath())));
            return file;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    private static void viewLayout(View view, int width, int height) {
        int measureWidth = View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY);
        int measureHeight = View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY);
        view.measure(measureWidth, measureHeight);
        view.layout(0, 0, width, height);
    }

    private static Bitmap createBitmap(View view) {
        Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(bitmap);
        canvas.drawColor(Color.WHITE);
        view.draw(canvas);
        return bitmap;
    }

    /**
     * 将recylerview转成bitmap
     *
     * @param view         recycler view
     * @param headerHeight 拼接头的高度
     * @param headBitmap   拼接头的bitmap
     * @return
     */
    private static Bitmap shotRecyclerView(RecyclerView view, int headerHeight, Bitmap headBitmap) {
        BaseAdapter adapter = (BaseAdapter) view.getAdapter();
        Bitmap bigBitmap = null;

        if (adapter != null) {
            int size = adapter.getItemCount();
            size = size > 20 ? 20 : size;
            int height = headerHeight;
            Paint paint = new Paint();
            int iHeight = headerHeight;


            for (int i = 0; i < size; i++) {
                BaseViewHolder holder = adapter.createVH(view, adapter.getItemViewType(i));
                adapter.publicConvert(holder, adapter.getData().get(i));

                holder.itemView.measure(
                        View.MeasureSpec.makeMeasureSpec(view.getWidth(), View.MeasureSpec.EXACTLY),
                        View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
                holder.itemView.layout(0, 0, holder.itemView.getMeasuredWidth(),
                        holder.itemView.getMeasuredHeight());

                height += holder.itemView.getMeasuredHeight();
            }

            bigBitmap = Bitmap.createBitmap(view.getMeasuredWidth(), height, Bitmap.Config.RGB_565);
            Canvas bigCanvas = new Canvas(bigBitmap);

            bigCanvas.drawColor(Color.WHITE);
            bigCanvas.drawBitmap(headBitmap, 0, 0, paint);
            headBitmap.recycle();

            for (int i = 0; i < size; i++) {
                BaseViewHolder holder = adapter.createVH(view, adapter.getItemViewType(i));
                adapter.publicConvert(holder, adapter.getData().get(i));

                holder.itemView.measure(
                        View.MeasureSpec.makeMeasureSpec(view.getWidth(), View.MeasureSpec.EXACTLY),
                        View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
                holder.itemView.layout(0, 0, holder.itemView.getMeasuredWidth(),
                        holder.itemView.getMeasuredHeight());
                holder.itemView.setDrawingCacheEnabled(true);
                holder.itemView.buildDrawingCache();
                Bitmap drawingCache = holder.itemView.getDrawingCache();

                bigCanvas.drawBitmap(drawingCache, 0f, iHeight, paint);

                drawingCache.recycle();
                iHeight += drawingCache.getHeight();
            }
        }
        return bigBitmap;
    }


    /**
     * 将recylerview转成bitmap
     *
     * @param view recycler view
     * @return
     */
    public static Bitmap shotRecyclerView(RecyclerView view) {
        return shotRecyclerView(view,20);
    }

    /**
     * 将recylerview转成bitmap
     *
     * @param view recycler view
     * @return
     */
    public static Bitmap shotRecyclerView(RecyclerView view, int itemCount) {
        BaseAdapter adapter = (BaseAdapter) view.getAdapter();
        Bitmap bigBitmap = null;

        if (adapter != null) {
            int size = adapter.getItemCount();
            int headerCount = adapter.getHeaderLayoutCount();
            int footerCount = adapter.getFooterLayoutCount();
            size = size > itemCount ? itemCount : size;
            int height = 0;
            int iHeight = 0;
            Paint paint = new Paint();
            for (int i = 0; i < size - footerCount; i++) {
                View itemView;
                BaseViewHolder holder;
                if (headerCount!=0&&i==0){
                    itemView = adapter.getHeaderLayout();
                }else {
                    holder = adapter.createVH(view, adapter.getItemViewType(i));
                    itemView = holder.itemView;
                }

                itemView.measure(
                        View.MeasureSpec.makeMeasureSpec(view.getWidth(), View.MeasureSpec.EXACTLY),
                        View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
                itemView.layout(0, 0, itemView.getMeasuredWidth(),
                        itemView.getMeasuredHeight());
                height += itemView.getMeasuredHeight();
            }

            bigBitmap = Bitmap.createBitmap(view.getMeasuredWidth(), height, Bitmap.Config.RGB_565);
            Canvas bigCanvas = new Canvas(bigBitmap);
            for (int i = 0; i < size - footerCount; i++) {
                View itemView;
                BaseViewHolder holder=null;
                if (headerCount!=0&&i==0){
                    itemView = adapter.getHeaderLayout();
                }else {
                    holder = adapter.createVH(view, adapter.getItemViewType(i));
                    itemView = holder.itemView;
                }
                if (i - headerCount >= 0) {
                    adapter.publicConvert(holder, adapter.getData().get(i - headerCount));
                }

                itemView.measure(
                        View.MeasureSpec.makeMeasureSpec(view.getWidth(), View.MeasureSpec.EXACTLY),
                        View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
                itemView.layout(0, 0, itemView.getMeasuredWidth(),
                        itemView.getMeasuredHeight());
                itemView.setDrawingCacheEnabled(true);

                itemView.buildDrawingCache();
                Bitmap drawingCache = itemView.getDrawingCache();

                bigCanvas.drawBitmap(drawingCache, 0f, iHeight, paint);
                iHeight += drawingCache.getHeight();
            }
        }
        return bigBitmap;
    }
    /**
     * 保存bitmap到系统相册
     *
     * @param quality 图片质量
     */
    public static void savePicture(final Context context, Bitmap bitmap, int quality) {
        String name = System.currentTimeMillis() + ".jpg";
        //生成路径
        String root = Environment.getExternalStorageDirectory().getAbsolutePath();
        String dirName = context.getResources().getString(R.string.app_name);
        File appDir = new File(root, dirName);
        if (!appDir.exists()) {
            appDir.mkdirs();
        }
        File file = new File(appDir,name);
        FileOutputStream outputStream=null;
        try {
            outputStream = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
            //其次把文件插入到系统图库

//            MediaStore.Images.Media.insertImage(context.getContentResolver(),
//            file.getAbsolutePath(), name, null);

            // 通知图库更新
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                MediaScannerConnection.scanFile(context, new String[]{file.getAbsolutePath()}, null,
                        new MediaScannerConnection.OnScanCompletedListener() {
                            @Override
                            public void onScanCompleted(String path, Uri uri) {
                                Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                                mediaScanIntent.setData(uri);
                                context.sendBroadcast(mediaScanIntent);
                            }
                        });
            } else {
                String relationDir = file.getParent();
                File file1 = new File(relationDir);
                context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.fromFile(file1.getAbsoluteFile())));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            bitmap.recycle();
            if (outputStream!=null){
                try {
                    outputStream.flush();
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    /**
     * 保存bitmap到系统相册
     *
     * @param quality 图片质量
     *                TODO          微博图片的时候不释放资源，会造成资源找不到
     */
    public static void savePicture(Context context, Bitmap bitmap, int quality, boolean b) {


        LogUtils.d("tingim", "savepic");
        String name = System.currentTimeMillis() + ".jpg";
        File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + File.separator + name);
        if (b) {
            try {
                FileOutputStream outputStream = new FileOutputStream(file);
                bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
                outputStream.flush();
                outputStream.close();
//                String uri = MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), name, null);
                //不保存缩略图
                ToastUtil.show(context,"图片已保存");
                Uri uri = Uri.fromFile(file);
                if (uri != null) {
                    try {
                        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_STARTED, uri));
                    } catch (Exception e) {
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 保存bitmap到系统相册
     *
     * @param quality 图片质量
     */
    public static String savePictureAndReturnPath(Context context, Bitmap bitmap, int quality) {

        String name = System.currentTimeMillis() + ".jpg";
        File dir = new File(ImageTools.app_file_dir, "captured_photos");
        String tmpDir = dir.getAbsolutePath();
        if (!FileUtil.makeDir(tmpDir)) {
            ToastUtil.show("创建文件目录失败");
            return "";
        }
        File file = new File(tmpDir + File.separator + name);
        try {
            FileOutputStream outputStream = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
            outputStream.flush();
            outputStream.close();
            bitmap.recycle();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file.getAbsolutePath();
    }


    /**
     * 截取普通的view
     *
     * @return 返回Bitmap
     */
    public static Bitmap shotView(View view) {
        int height = 0;
        if (view instanceof ScrollView|| view instanceof NestedScrollView) {
            ViewGroup viewGroup = (ViewGroup) view;
            for (int i = 0; i < viewGroup.getChildCount(); i++) {
                height += viewGroup.getChildAt(i).getHeight();
            }
        } else {
            height = view.getHeight();
        }
        if (view instanceof NestedScrollView){
            int max = DimentionsUtil.dp2px(view.getContext(),1092);
            height = height > max? max:height;
        }
        Bitmap bitmap = Bitmap.createBitmap(view.getMeasuredWidth(), height, Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(bitmap);
        view.draw(canvas);
        return bitmap;
    }

    /**
     * 等比缩放工具类
     */
    public static Bitmap zoomImg(Bitmap bm, int newWidth) {
        // 获得图片的宽高
        int width = bm.getWidth();
        int height = bm.getHeight();
        if (width == newWidth) return bm;
        // 计算缩放比例
        float scaleWidth = ((float) newWidth) / width;
        // 取得想要缩放的matrix参数
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleWidth);
        // 得到新的图片
        return Bitmap.createBitmap(bm, 0, 0, width, height, matrix, true);
    }
}
